package servlet;

import user.ShopCar;
import util.DBUtilDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class SubUpdateShopServlet extends HttpServlet {//减少购物车

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {
            response.getWriter().println("请先登录！！！（2秒后自动跳转）");
            response.setHeader("refresh", "2;URL=login.jsp");
        } else {
            DBUtilDao dbUtilDao = new DBUtilDao();
            String phoneNumber = (String) request.getSession().getAttribute("username");
            String fruit = request.getParameter("fruit");
            ShopCar shopCar = null;
            if (fruit.equals("orange")) {
                shopCar = new ShopCar(phoneNumber, 1, 88, "orange");
            } else if (fruit.equals("apple")) {
                shopCar = new ShopCar(phoneNumber, 1, 88, "apple");
            }
            try {
                //首先判断购物车中商品的数量是否大于0
                List<ShopCar> list = dbUtilDao.getShopCar(shopCar);
                for (ShopCar shopCar1 : list) { //遍历查询结果集
                    if (shopCar1.getNumber() > 1) {
                        dbUtilDao.subUpdateShopCar(shopCar); //更新数据库中的购物车
                    } else {
                        dbUtilDao.deleteShopCar(shopCar); //删除当前用户的当前商品
                        request.getSession().removeAttribute("result");
                    }
                    dbUtilDao.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }


            SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
            selectShopCarServlet.doGet(request, response); //刷新购物车的页面
            response.sendRedirect("shopcar.jsp");
        }
    }
}
